<?php
declare (strict_types=1);

namespace app\api\controller;

use app\api\controller\Base;
use app\common\model\Order;
use app\common\model\User;
use app\common\model\TaskList as TaskListmodel;
use app\common\server\RedisLock as Lock;
use think\facade\Db;
use \think\Request;

class TaskList extends Base
{
    /***
     * 每日/每周任务
     * @param Request $request
     * @return \think\response\Json
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function task_list(Request $request){
        $user = $this->getUser();
        $type = request()->param('type/d', 1);
        $where = [];
        $where[] = ['type','=',$type];
        $field = 'id,type,cate,title,number,z_number';
        $task_list = \app\common\model\TaskList::getAllList($where,$field,'sort desc,id desc');

        foreach ($task_list as $k => &$v){
            //1每日任务   2每周任务
            if ($v['type'] == 1){
                $start_time = strtotime(date('Y-m-d',time()).' 00:00:00');
                $end_time = strtotime(date('Y-m-d',time()).' 23:59:59');
            }else{
                $date = date('Y-m-d');  //当前日期
                $first = 1; //$first =1 表示每周星期一为开始日期 0表示每周日为开始日期
                $w = date('w', strtotime($date));  //获取当前周的第几天 周日是 0 周一到周六是 1 - 6
                $to_day = date('Y-m-d', strtotime("$date -" . ($w ? $w - $first : 6) . ' days')); //获取本周开始日期，如果$w是0，则表示周日，减去 6 天
                $to_day2 = $to_day;
                $start_time = strtotime($to_day);
                $end_time = strtotime(date('Y-m-d', strtotime("$to_day2 + 6 days")) . ' 23:59:59');  //本周结束日期
            }
            //1邀请好友注册  2抽赏任务
            if ($v['cate'] == 1){
                $yao_count = \app\common\model\User::where([['pid','=',$user['id']],['addtime','>=',$start_time]])->count();
                if ($yao_count >= $v['number']) {
                    $v['is_complete'] = 1;
                    //进度条
                    $v['percentage'] = 100;
                    //已完成数量
                    $v['ywc_count'] = $v['number'];
                } else {
                    $v['is_complete'] = 0;
                    //进度条
                    $v['percentage'] = round(($yao_count / $v['number']) * 100);
                    //已完成数量
                    $v['ywc_count'] = $yao_count;
                }
                $v['pages'] = '/pages/user/tui-guang';
            }elseif ($v['cate'] == 2){
                $prize_num = Order::where([['user_id','=',$user['id']],['status','=',1],['addtime','>=',$start_time]])->count();
                if ($prize_num >= $v['number']) {
                    $v['is_complete'] = 1;
                    //进度条
                    $v['percentage'] = 100;
                    //已完成数量
                    $v['ywc_count'] = $v['number'];
                } else {
                    $v['is_complete'] = 0;
                    //进度条
                    $v['percentage'] = round(($prize_num / $v['number']) * 100);
                    //已完成数量
                    $v['ywc_count'] = $prize_num;
                }
                 $v['pages'] = '/pages/shouye/index';
            }
            //是否已领取
            $is_ling = Db::name('user_task_list')->field('id')->where([['user_id','=',$user['id']],['task_list_id','=',$v['id']],['addtime','>=',$start_time],['addtime','<=',$end_time]])->whereNull('deltime')->find();
            if ($is_ling){
                $v['is_complete'] = 2;
            }
        }
        return $this->renderSuccess("请求成功", compact('task_list'));
    }

    /**
     * 领取任务
     * @param Request $request
     * @return \think\response\Json
     */
    public function ling_task(Request $request){
        $user = $this->getUser();
        $task_list_id = request()->param('task_list_id/d', 0);
        $task_list = TaskListmodel::getInfo(['id' => $task_list_id]);
        if (!$task_list){
            return $this->renderError("任务不存在");
        }

        //1每日任务   2每周任务
        if ($task_list['type'] == 1){
            $start_time = strtotime(date('Y-m-d',time()).' 00:00:00');
            $end_time = strtotime(date('Y-m-d',time()).' 23:59:59');
        }else{
            $date = date('Y-m-d');  //当前日期
            $first = 1; //$first =1 表示每周星期一为开始日期 0表示每周日为开始日期
            $w = date('w', strtotime($date));  //获取当前周的第几天 周日是 0 周一到周六是 1 - 6
            $to_day = date('Y-m-d', strtotime("$date -" . ($w ? $w - $first : 6) . ' days')); //获取本周开始日期，            如果$w是0，则表示周日，减去 6 天
            $to_day2 = $to_day;
            $start_time = strtotime($to_day);
            $end_time = strtotime(date('Y-m-d', strtotime("$to_day2 + 6 days")) . ' 23:59:59');  //本周结束日期
        }
        //1邀请好友注册  2抽赏任务
        if ($task_list['cate'] == 1){
            $yao_count = \app\common\model\User::where([['pid','=',$user['id']],['addtime','>=',$start_time]])->count();
            if ($yao_count < $task_list['number']) {
                return $this->renderError("任务未完成");
            }
        }elseif ($task_list['cate'] == 2){
            // $prize_num = Order::where([['user_id','=',$user['id']],['status','=',1],['addtime','>=',$start_time]])->count();
            
            $prize_num = Order::where([['user_id','=',$user['id']],['status','=',1],['addtime','>=',$start_time]])->sum('prize_num');
            // dd($prize_num, $task_list['number']);
            if ($prize_num < $task_list['number']) {
                return $this->renderError("任务未完成");
            }
        }

        $is_ling = Db::name('user_task_list')->field('id')->where([['user_id','=',$user['id']],['task_list_id','=',$task_list_id],['addtime','>=',$start_time],['addtime','<=',$end_time]])->whereNull('deltime')->find();
        if ($is_ling){
            return $this->renderError("你已经领取过了");
        }

        Db::startTrans();
        $data = [];
        $data['user_id'] = $user['id'];
        $data['task_list_id'] = $task_list_id;
        $data['type'] = $task_list['type'];
        $data['cate'] = $task_list['cate'];
        $data['is_important'] = $task_list['is_important'];
        $data['number'] = $task_list['number'];
        $data['z_number'] = $task_list['z_number'];
        $data['addtime'] = time();
        $data['updatetime'] = time();
        $result = Db::name('user_task_list')->insert($data);

        if ($task_list['z_number'] > 0){
            User::changeScore($user['id'], $task_list['z_number'], 7, '完成任务领取');

            // User::changeOuQi($user['id'],$task_list['z_number'],1,'完成任务');
            // User::ou_qi_level_up($user['id'],$task_list['z_number'],2);
            
        }
        if ($result){
            Db::commit();
            return $this->renderSuccess("领取成功");
        }else{
            Db::rollback();
            return $this->renderError("网络故障, 请稍后再试");
        }
    }

}